package com.tsky.system.manager.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.tsky.casing.QueryBean;
import com.tsky.casing.orm.impl.EntityManagerImpl;
import com.tsky.common.BeanUtil;
import com.tsky.system.entity.Constant;
import com.tsky.system.manager.ConstantManager;
import com.tsky.system.query.ConstantQuery;

@Repository("constantManager")
public class ConstantManagerImpl extends EntityManagerImpl implements ConstantManager {

	public void query(QueryBean queryBean) {
		// TODO Auto-generated method stub
		ConstantQuery query = (ConstantQuery) queryBean;
		
		// 基本查询条件
		int page = queryBean.getPage();
		int pageSize = queryBean.getRows(); // page size
		String orderField = queryBean.getSort();
		String sortOrder = queryBean.getOrder();
		
		// 组合查询条件
		String fieldName = query.getFieldName();
		String status = query.getStatus();
		String showValue = query.getShowValue();
		
		Criteria ctr = this.getSession().createCriteria(Constant.class);

		// 组合查询
		if (!BeanUtil.isEmpty(status) && !"3".equals(status)) {
			ctr.add(Restrictions.eq("status", status));
		}
		
		if (!BeanUtil.isEmpty(fieldName)) {
			ctr.add(Restrictions.like("fieldName", "%" + fieldName + "%"));
		}
		
		if (!BeanUtil.isEmpty(showValue)) {
			ctr.add(Restrictions.like("showValue", "%" + showValue + "%"));
		}
		
		// 排序
		if (!BeanUtil.isEmpty(sortOrder)) {
			if ("asc".equals(sortOrder)) {
				ctr.addOrder(Order.asc(orderField));
			} else {
				ctr.addOrder(Order.desc(orderField));
			}
		}
		
		// 总记录数
		List<?> resultList = ctr.list();
		queryBean.setTotal(resultList.size());

		ctr.setFirstResult(pageSize * (page - 1));
		ctr.setMaxResults(pageSize);
		
		queryBean.setDataList(ctr.list());
	}

	public void queryAll(QueryBean queryBean) {
		ConstantQuery query = (ConstantQuery) queryBean;
		
		// 组合查询条件
		String fieldName = query.getFieldName();
		String status = query.getStatus();
		String showValue = query.getShowValue();
		
		Criteria ctr = this.getSession().createCriteria(Constant.class);

		// 组合查询
		if (!BeanUtil.isEmpty(status) && !"3".equals(status)) {
			ctr.add(Restrictions.eq("status", status));
		}
		
		if (!BeanUtil.isEmpty(fieldName)) {
			ctr.add(Restrictions.like("fieldName", "%" + fieldName + "%"));
		}
		
		if (!BeanUtil.isEmpty(showValue)) {
			ctr.add(Restrictions.like("showValue", "%" + showValue + "%"));
		}
		
		// 总记录数
		List<?> resultList = ctr.list();
		queryBean.setTotal(resultList.size());

		queryBean.setDataList(resultList);
	}

}
